import React, { Key, useEffect, useState } from "react";
import { useLocation, Location } from "react-router-dom";
import {
  getHospitalDepartmentRequest,
  getScheduleRuleListRequest,
  findScheduleListRequest,
} from "@/api/hospital/hospitalList";
import type {
  bookingScheduleListType,
  findScheduleListType,
  getHospitalDepartmentListType,
} from "@/api/hospital/model/hospitalListTypes";
import { Card, Col, Row, Tree, Tag, Pagination, Table, message } from "antd";
export default function HospitalSchedule() {
  //自定义hook，传递泛型
  function useMyLocation<T>() {
    type L = Location & T;
    return useLocation() as { state: L };
  }
  const { hoscode } = useMyLocation<{ hoscode: string }>().state;
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(3);
  const [total, setTotal] = useState(0);
  const [depCode, setDepCode] = useState("");
  const [workDate, setWorkDate] = useState("");
  const [departmentList, setDepartmentList] =
    useState<getHospitalDepartmentListType>([]);
  const [scheduleRuleList, setScheduleRuleList] =
    useState<bookingScheduleListType>([]);
  const [dataSource, setDataSource] = useState<findScheduleListType>([]);
  const [isLoading, setIsLoading] = useState(false);

  //初始化副作用
  useEffect(() => {
    const getDepList = async () => {
      const re = await getHospitalDepartmentRequest(hoscode);
      setDepartmentList(re);
      setDepCode(re[0].children[0].depcode);
      // console.log(re);
    };
    getDepList();
  }, []);

  //科室改变副作用
  useEffect(() => {
    if (!depCode) return;
    setIsLoading(true);
    const getScheduleRule = async () => {
      const re = await getScheduleRuleListRequest({
        page,
        limit,
        hoscode: hoscode as string,
        depcode: depCode,
      });
      // console.log(re);
      setScheduleRuleList(re.bookingScheduleList);
      setTotal(re.total);
      //如果没有直接返回空
      setWorkDate(re.bookingScheduleList[0]?.workDate);
      setIsLoading(false);
    };
    getScheduleRule();
  }, [depCode, page, limit]);

  //页码，选项卡点击改变的副作用
  useEffect(() => {
    //如果没有安排时间。则设置一个空数据
    if (!workDate) return setDataSource([]);
    setIsLoading(true);
    const getDataSource = async () => {
      const re = await findScheduleListRequest(hoscode, depCode, workDate);
      // console.log(re);
      setDataSource(re);
      setIsLoading(false);
    };

    getDataSource();
  }, [workDate]);
  //切换科室的事件回调
  const departmentSwitchHandle = (depCodeArr: Key[]) => {
    const depcode = depCodeArr[0] as string;
    setDepCode(depcode);
  };
  //切换页码的事件回调
  const pageChangeHandle = (current: number, pageSize: number) => {
    setPage(current);
    setLimit(pageSize);
  };
  //切换选项的事件回调
  const tapChangeHandle = (workDate: string) => {
    return () => {
      setWorkDate(workDate);
    };
  };

  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "可预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "挂号费用",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];
  return (
    <Card>
      <p>选择:北京协和医院/多发性硬化专科门诊/2022-04-08</p>
      <Row gutter={20}>
        <Col span={5}>
          <div>
            <Tree
              onSelect={departmentSwitchHandle}
              expandedKeys={["a4e171f4cf9b6816acdfb9ae62c414d7"]}
              treeData={departmentList as []}
              fieldNames={{ title: "depname", key: "depcode" }}
              style={{
                overflow: "auto",
                border: "1px solid #000",
                height: "480px",
              }}
            />
          </div>
        </Col>
        <Col span={19}>
          <div>
            {scheduleRuleList.map((item) => {
              return (
                <Tag
                  color="green"
                  key={item.workDate}
                  //当前时间与现在触发事件的选项的时间一致就使其高亮
                  style={{
                    cursor: "pointer",
                    background: item.workDate === workDate ? "skyblue" : "",
                  }}
                  onClick={tapChangeHandle(item.workDate)}
                >
                  <p>{item.workDate}</p>
                  <p>{`${item.availableNumber}/${item.reservedNumber}`}</p>
                </Tag>
              );
            })}
          </div>
          {/* 分页器组件 */}
          <Pagination
            style={{ marginTop: 20 }}
            current={page}
            pageSize={limit}
            total={total}
            onChange={pageChangeHandle}
          />
          <Table
            loading={isLoading}
            style={{ marginTop: 20 }}
            columns={columns}
            bordered
            rowKey="id"
            dataSource={dataSource}
            pagination={false}
          />
        </Col>
      </Row>
    </Card>
  );
}
